package com.dacool.config;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.util.Log;

import com.dacool.http.BaseRequest;
import com.dacool.http.BaseRequest.ResponseHandler;
import com.dacool.http.GetPayMethodRequest;
import com.dacool.http.GetRegionRequest;
import com.dacool.model.DCPayMethod;
import com.dacool.model.Region;
import com.dacool.util.DataStateMonitor;
import com.dacool.util.FileCacheUtil;
import com.dacool.util.ObservedData;
import com.dacool.util.ViewUtils;

public class Config implements Serializable, ObservedData {
	/**
	 * 
	 */
	private static final long serialVersionUID = 8541566936775492912L;

	public static final String host = "http://app.dacool.com/dcmapp/api/";

	private String dev_host = "http://app.dacool.com/dcmapp/api/";

	private final static Region[] default_districts = new Region[] {
			new Region(1, "北京", 0), new Region(21, "上海", 0),
			new Region(814, "河北", 0) };

	public ArrayList<Region> districts;

	private final static String[] default_payMethods = new String[] { "财付通" };

	private final static int[] default_payMethodIds = new int[] { 1 };

	public void setDevHost(String dev_host) {
		this.dev_host = dev_host;
	}

	public ArrayList<DCPayMethod> payMethods;

	public static final String APP_SECRET = "fba95e7bd17ed3ba3620adda9ed5f03d";

	public static final boolean DEV_MODE = true;

	private Config() {
		payMethods = new ArrayList<DCPayMethod>();
	}

	private static Config sharedConfig;

	public static Config sharedConfig() {
		if (sharedConfig == null) {
			sharedConfig = new Config();
		}
		return sharedConfig;
	}

	public void load() {
		Config config = (Config) FileCacheUtil.readObject(
				ViewUtils.getContext(), "config");
		if (config == null) {
			districts = new ArrayList<Region>(Arrays.asList(default_districts));
			dev_host = host;
			DCPayMethod paymethod = new DCPayMethod();
			payMethods.clear();
			paymethod.id = default_payMethodIds[0];
			paymethod.name = default_payMethods[0];
			payMethods.add(paymethod);
		} else {
			districts = config.districts;
			dev_host = config.dev_host;
			payMethods = config.payMethods;
			cookies = config.cookies;
			cookieExpireDate = config.cookieExpireDate;
		}
	}

	public String getHost() {
		return DEV_MODE ? dev_host : host;
	}

	public ArrayList<Region> getRegionsByParentID(int parentID) {
		ArrayList<Region> returnRegions = new ArrayList<Region>();
		for (Region region : districts) {
			if (region.parentId == parentID) {
				returnRegions.add(region);
			}
		}
		return returnRegions;
	}

	public Region getRegionById(int id) {
		for (Region region : districts) {
			if (region.id == id) {
				return region;
			}
		}
		return null;
	}

	public HashMap<String, String> cookies = new HashMap<String, String>();

	public Date cookieExpireDate = null;

	public void init() {
		this.load();
		if (cookieExpireDate != null && cookieExpireDate.before(new Date())) {
			cookies.clear();
			this.save();
		}

		new GetRegionRequest().setParentId(0).setHandler(new ResponseHandler() {

			/**
			 *  [ {id:”1”, "name": "北京"}, {id:”2”, "name": "上海},{id:”3”, "name
			 * ": "河北"}]
			 */
			@Override
			public void handleResponse(BaseRequest request, int statusCode,
					String errorMsg, String response) {
				// TODO Auto-generated method stub
//				Log.d("test", "response:" + response);
				if (statusCode != 200)
					return;
				try {
					JSONObject data = new JSONObject(response);
					JSONArray array = data.getJSONArray("data");
					districts = new ArrayList<Region>();
					for (int i = 0; i < array.length(); i++) {
						JSONObject obj = array.getJSONObject(i);
						Region region = new Region(obj.getInt("regionId"), obj
								.getString("localName"), obj.optInt(
								"pregionId", 0));
						districts.add(region);
					}
					Config.this.save();
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

			}
		}).start();

		new GetPayMethodRequest().setHandler(new ResponseHandler() {

			@Override
			public void handleResponse(BaseRequest request, int statusCode,
					String errorMsg, String response) {
				if (statusCode != 200)
					return;
				else {
					boolean success = false;
					ArrayList<DCPayMethod> methods = new ArrayList<DCPayMethod>();
					try {
						JSONObject object = new JSONObject(response);
						success = object.optBoolean("success", false);
						JSONArray array = object.getJSONArray("data");
						for (int i = 0; i < array.length(); i++) {
							JSONObject obj = array.getJSONObject(i);
							DCPayMethod method = new DCPayMethod();
							method.id = obj.getInt("paymethod_id");
							method.name = obj.getString("paymethod_name");
							methods.add(method);
						}
					} catch (JSONException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}

					if (success) {
						Config.this.payMethods = payMethods;
						Config.this.save();
					}
				}
			}
		}).start();
	}

	public void save() {
		FileCacheUtil.writeObject(ViewUtils.getContext(), this, "config");
	}

	@Override
	public void addMonitor(DataStateMonitor monitor) {
		// TODO Auto-generated method stub

	}

	@Override
	public void removeMonitor(DataStateMonitor monitor) {
		// TODO Auto-generated method stub

	}

	@Override
	public void notifyMonnitors() {
		// TODO Auto-generated method stub

	}

}
